package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.RecommendUser;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import javax.swing.*;
import java.util.List;

@DubboService
public class RecommendUserServiceImp implements RecommendUserService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override//查询今日佳人
    public RecommendUser findMaxScoreRecommendUser(Long toUserId) {
        //创建条件为被推荐人相同、按照缘分值降序、查询第一个
        Query query = new Query(Criteria.where("toUserId").is(toUserId))
                .with(Sort.by(Sort.Order.desc("score")))
                .skip(0).limit(1);
        //调用mongo查询出今日佳人
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        //返回结果
        return recommendUser;
    }

    @Override//查询推荐列表
    public PageBeanVo findRecommendUserByPage(Long toUserId, Integer pageNum, Integer pageSize) {
        //计算开始索引
        Integer index = (pageNum - 1) * pageSize;
        //创建条件为被推荐id相同、缘分值降序、并分页
        Query query = new Query(Criteria.where("toUserId").is(toUserId))
                .with(Sort.by(Sort.Order.desc("score")))
                .skip(index + 1).limit(pageSize);
        //调用mongo查询出满足条件的推荐列表用户
        List<RecommendUser> recommendUsers = mongoTemplate.find(query, RecommendUser.class);
        //调用mongo查询出满足条件的用户数量
        long count = mongoTemplate.count(query, RecommendUser.class);
        //返回分页类
        return new PageBeanVo(pageNum, pageSize, count, recommendUsers);
    }

    @Override//查询推荐用户详情
    public RecommendUser findRecommendUserByCondition(Long toUserId, Long userId) {
        //创建条件为被推荐id和推荐id相同
        Query query = new Query(Criteria.where("toUserId").is(toUserId)
                .and("userId").is(userId));
        //调用mongo查询出满足条件的推荐用户
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        //返回结果
        return recommendUser;
    }

    @Override//删除推荐用户动态
    public void remove(Long toUserId, Long userId) {
        Query query=new Query(Criteria.where("toUserId").is(toUserId)
        .and("userId").is(userId));
        mongoTemplate.remove(query,RecommendUser.class);
    }
}
